<template>
  <div id="addQuestionView">
    <div class="form-container">
      <a-form :model="form" label-align="left" auto-label-width>
        <a-form-item field="title" label="标题" :style="{ width: '520px' }">
          <a-input
            v-model="form.title"
            allow-clear
            placeholder="请输入标题"
            style="border-radius: 10px"
            size="large"
          />
        </a-form-item>
        <a-form-item
          field="difficulty"
          label="标签"
          :style="{ width: '520px' }"
        >
          <a-select
            size="large"
            v-model="form.tagList"
            placeholder="请选择标签 ..."
            multiple
            style="border-radius: 10px"
          >
            <a-optgroup label="所属领域">
              <a-option>Java</a-option>
              <a-option>C++</a-option>
              <a-option>Python</a-option>
              <a-option>VUE</a-option>
              <a-option>JS</a-option>
            </a-optgroup>
            <a-optgroup label="编程类别">
              <a-option>后端</a-option>
              <a-option>前端</a-option>
              <a-option>全栈</a-option>
              <a-option>测试</a-option>
              <a-option>算法</a-option>
            </a-optgroup>
            <a-optgroup label="其他">
              <a-option>面经</a-option>
              <a-option>求职</a-option>
              <a-option>面试</a-option>
              <a-option>经验</a-option>
              <a-option>技巧</a-option>
              <a-option>校招</a-option>
              <a-option>社招</a-option>
            </a-optgroup>
          </a-select>
        </a-form-item>
        <div style="margin-top: 16px" />
        <a-form-item field="content" label="封面">
          <a-avatar
            class="postCover"
            :imageUrl="form.cover"
            :style="{
              transform: 'scale(2.8)',
            }"
            shape="square"
          >
          </a-avatar>
          <a-trigger>
            <a-avatar
              style="
                transform: translateY(40px) translateX(-2px) scale(0.9);
                border: 3px solid #fff;
                cursor: pointer;
              "
              :style="{ backgroundColor: '#E0F4E7' }"
            >
              <IconEdit style="color: #2db55d" />
            </a-avatar>
            <template #content>
              <div
                style="
                  box-shadow: 0 0 4px rgba(0, 0, 0, 0.2);
                  padding: 8px;
                  border-radius: 5px;
                  background-color: white;
                "
              >
                <a-space direction="vertical" fill>
                  <a-upload
                    action="/"
                    :show-file-list="false"
                    @change="handleFileUpload"
                    :limit="1"
                  >
                    <template #upload-button>
                      <a-button style="border-radius: 3px">上传封面</a-button>
                    </template>
                  </a-upload>
                  <a-button @click="form.cover = ''" style="border-radius: 3px"
                    >删除封面
                  </a-button>
                </a-space>
              </div>
            </template>
          </a-trigger>
        </a-form-item>
        <a-form-item style="margin-top: 35px" field="content" label="帖子内容">
          <div>
            <!-- <AiEditor :value="form.content" :handle-change="onContentChange" />-->
            <MdEditor :value="form.content" :handle-change="onContentChange" />
          </div>
        </a-form-item>
        <a-form-item>
          <div style="min-width: 200px; z-index: 0">
            <a-button
              type="primary"
              @click="doSubmit"
              style="border-radius: 20px"
              >提交
            </a-button>
          </div>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  FileControllerService,
  PostControllerService,
  QuestionControllerService,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRoute, useRouter } from "vue-router";
import AiEditor from "@/components/AiEditor.vue";
import MonacoEditor from "@/components/MonacoEditor.vue";
import { FileItem } from "@arco-design/web-vue";
import MdEditor from "@/components/MdEditor.vue";

const route = useRoute();
const router = useRouter();
// 如果页面地址包含 update，视为更新页面
const updatePage = route.path.includes("update");

let form = ref({
  title: "",
  tags: [],
  tagList: [],
  content: "",
  cover: "",
});

/**
 * 根据题目 id 获取老的数据
 */
const loadData = async () => {
  const id = route.query.id;
  if (!id) {
    return;
  }
  const res = await PostControllerService.getPostVoByIdUsingGet(id as any);
  if (res.code === 0) {
    form.value = res.data as any;
  } else {
    message.error("加载失败，" + res.message);
  }
};
onMounted(() => {
  loadData();
});

const doSubmit = async () => {
  // 区分更新还是创建
  if (updatePage) {
    const res = await PostControllerService.editPostUsingPost(form.value);
    if (res.code === 0) {
      message.success("更新成功");
      await router.push("/post");
    } else {
      message.error("更新失败，" + res.message);
    }
  } else {
    console.log(form.value);
    const res = await PostControllerService.addPostUsingPost(form.value);
    if (res.code === 0) {
      message.success("创建成功");
      await router.push("/post");
      router.go(-1);
    } else {
      message.error("创建失败:" + res.message);
    }
  }
};

const onContentChange = (value: string) => {
  form.value.content = value;
};

// 处理文件上传
const handleFileUpload = async (fileList: FileItem[]) => {
  console.log("handleFileUpload", fileList[0]);
  const file = fileList[0].file;
  if (file) {
    const response = await FileControllerService.uploadFileUsingPost(
      "user_avatar",
      file as any
    );
    if (response.code == 0) {
      // 上传成功
      form.value.cover = response.data;
    } else {
      // 上传失败
      message.error("上传失败：" + response.message);
    }
    console.log("已选择文件:", file);
    // 可以在这里继续处理其他逻辑，例如预览图片等
  }
};
</script>

<style scoped>
#addQuestionView {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f7f8fa;

  .form-container {
    margin-top: 30px;
  }
  .postCover {
    margin-top: 20px;
    margin-left: 35px;
  }
}
</style>
